





from django.apps import AppConfig
from django.core import checks
from django.db.models.signals import post_migrate

class MyappConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'myapp'
    verbose_name = "核心应用"
    
    # 自定义配置选项
    ENABLE_USER_ACTIVITY_TRACKING = True
    DEFAULT_USER_ACTIVITY_COUNT = 0
    
    def ready(self):
        """
        应用就绪时执行的高级初始化
        """
        # 1. 导入并注册信号处理器
        self._register_signals()
        
        # 2. 注册迁移后操作
        post_migrate.connect(self.create_initial_data, sender=self)
        
        # 3. 动态添加模型权限
        self._add_custom_permissions()
        
        # 4. 验证应用设置
        self._validate_settings()
        
        print(f"✅ {self.verbose_name} 已初始化完成")
    
    def _register_signals(self):
        """注册信号处理器"""
        from . import signals
        from logger.receivers import log_user_visit, log_user_activity
        
        signals.user_visited.connect(
            log_user_visit, 
            dispatch_uid="log_user_visit"
        )
        
        if self.ENABLE_USER_ACTIVITY_TRACKING:
            signals.user_activity.connect(
                log_user_activity,
                dispatch_uid="log_user_activity"
            )
    
    # 使用装饰器注册检查函数
    @staticmethod
    @checks.register('models')
    def check_user_model_config(**kwargs):
        """
        自定义系统检查：验证用户模型配置
        """
        from django.conf import settings
        from django.core.checks import Error
        
        errors = []
        
        # 检查 AUTH_USER_MODEL 是否配置
        if not hasattr(settings, 'AUTH_USER_MODEL'):
            errors.append(
                Error(
                    'AUTH_USER_MODEL 未配置',
                    hint='在 settings.py 中设置 AUTH_USER_MODEL',
                    id='myapp.E001',
                )
            )
        
        # 检查配置的用户模型是否匹配
        elif settings.AUTH_USER_MODEL != 'myapp.CustomUser':
            errors.append(
                Error(
                    'AUTH_USER_MODEL 配置错误',
                    hint=f'应为 myapp.CustomUser，当前为 {settings.AUTH_USER_MODEL}',
                    id='myapp.E002',
                )
            )
        
        return errors
    
    def create_initial_data(self, sender, **kwargs):
        """
        迁移后创建初始数据
        """
        from django.db import connection, OperationalError
        from django.contrib.auth import get_user_model
        
        # 检查用户表是否存在
        table_name = "myapp_customuser"
        
        try:
            # 检查表是否存在
            with connection.cursor() as cursor:
                cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'")
                table_exists = cursor.fetchone() is not None
            
            if not table_exists:
                print(f"⚠️ 警告: 表 {table_name} 不存在，跳过创建初始用户")
                return
                
            User = get_user_model()

            print("------create_initial_data--------", User)
            
            # 创建初始超级用户
            if not User.objects.filter(is_superuser=True).exists():
                User.objects.create_superuser(
                    username='admin',
                    email='admin@example.com',
                    password='adminpassword',
                    activity_count=self.DEFAULT_USER_ACTIVITY_COUNT
                )
                print("🚀 已创建初始超级用户: admin/adminpassword")
        except OperationalError as e:
            print(f"⚠️ 警告: 数据库操作失败: {e}")
        except Exception as e:
            print(f"⚠️ 警告: 创建初始用户时发生错误: {e}")
    
    def _add_custom_permissions(self):
        """动态添加自定义权限"""
        from django.db import connection, OperationalError
        from django.contrib.auth.models import Permission
        from django.contrib.contenttypes.models import ContentType
        from .models import CustomUser
        
        # 检查内容类型表是否存在
        try:
            with connection.cursor() as cursor:
                cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='django_content_type'")
                content_type_table_exists = cursor.fetchone() is not None
            
            if not content_type_table_exists:
                print("⚠️ 警告: django_content_type 表不存在，跳过添加权限")
                return
                
            user_content_type = ContentType.objects.get_for_model(CustomUser)
            
            # 添加自定义权限
            custom_permissions = [
                ('can_view_advanced_analytics', '可以查看高级分析'),
                ('can_export_data', '可以导出数据'),
            ]
            
            for codename, name in custom_permissions:
                Permission.objects.get_or_create(
                    codename=codename,
                    name=name,
                    content_type=user_content_type
                )
        except OperationalError as e:
            print(f"⚠️ 警告: 数据库操作失败: {e}")
        except Exception as e:
            print(f"⚠️ 警告: 添加自定义权限时出错: {e}")
    
    def _validate_settings(self):
        """验证应用相关设置"""
        from django.conf import settings
        
        # 确保启用了会话中间件
        if 'django.contrib.sessions.middleware.SessionMiddleware' not in settings.MIDDLEWARE:
            print("⚠️ 警告: SessionMiddleware 未启用，用户认证可能无法正常工作")